package com.project.config.shiro;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.project.bean.system.TblRoleBean;
import com.project.bean.system.TblUserBean;
import com.project.entity.system.user.UserInfoEntity;
import com.project.service.system.UserService;
import com.project.utils.token.JwtToken;
import com.project.utils.token.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.beetl.sql.core.BeetlSQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @author SPPan
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    public MyRealm() {
        super(new AllowAllCredentialsMatcher());
        setAuthenticationTokenClass(JwtToken.class);
    }


    /**
     * 设置 角色 和 资源
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        UserInfoEntity userInfoEntity = ShiroUtils.getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(userInfoEntity.getUserName().equals("admin")){
            info.addRole("admin");
            info.addStringPermission("*:*:*");
            return info;
        }else{
            Set<String> shiroPermissions = new HashSet<>();
            Set<String> roleSet = new HashSet<String>();
            // 查询角色
            Set<TblRoleBean> roleList = userInfoEntity.getRoles();
            for (TblRoleBean tblRoleBean : roleList) {
                // 添加角色
                roleSet.add(tblRoleBean.getPermission());
            }
            info.setRoles(roleSet);
            info.setStringPermissions(shiroPermissions);
            return info;
        }

    }

    /**
     * 配置登陆
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        JwtToken upToken = (JwtToken) token;
        String tokenStr = (String) upToken.getPrincipal();
        String loginname = JwtUtil.getLoginname(tokenStr);
        String password = JwtUtil.getPassword(tokenStr);

        if (StrUtil.isEmpty(loginname)) {
            throw new UnknownAccountException("账号不能为空");
        }
        if (StrUtil.isEmpty(password)) {
            throw new UnknownAccountException("密码不能为空");
        }
        // 用户信息 包含角色
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        try {
            TblUserBean tblUserBean = new TblUserBean();
            tblUserBean.setUserName(loginname);
            tblUserBean.setPassWord(password);
            tblUserBean = userService.find_ObjByWhere(tblUserBean);
            if(ObjectUtil.isNull(tblUserBean)){
                throw new UnknownAccountException("账号密码错误");
            }
            // 获取角色
            List<TblRoleBean> roleList = userService.findRoleListByUserId(tblUserBean.getUserId());
            userInfoEntity = BeanUtil.toBean(tblUserBean, UserInfoEntity.class);
            userInfoEntity.setRoles(new HashSet<TblRoleBean>(roleList));

        } catch (BeetlSQLException e) {
            e.printStackTrace();
            throw new UnknownAccountException("数据库异常");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfoEntity, password, getName());
        return info;
    }

}
